package com.yunyi.web.controller.system;

import java.util.Date;
import java.sql.Wrapper;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.yunyi.common.annotation.Log;
import com.yunyi.common.core.controller.BaseController;
import com.yunyi.common.core.domain.AjaxResult;
import com.yunyi.common.core.domain.entity.SysDept;
import com.yunyi.common.core.domain.entity.SysRole;
import com.yunyi.common.core.domain.entity.SysUser;
import com.yunyi.common.core.page.TableDataInfo;
import com.yunyi.common.enums.BusinessType;
import com.yunyi.common.utils.SecurityUtils;
import com.yunyi.common.utils.StringUtils;
import com.yunyi.common.utils.poi.ExcelUtil;
import com.yunyi.system.service.ISysDeptService;
import com.yunyi.system.service.ISysPostService;
import com.yunyi.system.service.ISysRoleService;
import com.yunyi.system.service.ISysUserService;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    /**
     * UserService
     **/
    @Autowired
    private ISysUserService userService;

    /**
     * RoleService
     **/
    @Autowired
    private ISysRoleService roleService;

    /**
     * @Description: 用户列表条件分页
     * @Param [pageNum, pageSize, user]
     * @Return com.yunyi.common.core.domain.AjaxResult
     * @Throws
     **/
    @GetMapping("/userList")
    public AjaxResult selectUserList(Integer pageNum, Integer pageSize, SysUser user) {
        IPage<SysUser> userIPage = userService.selectUserList(pageNum, pageSize, user);
        AjaxResult result = AjaxResult.success(userIPage.getRecords());
        result.put("pageNum", userIPage.getCurrent());
        result.put("pageSize", userIPage.getSize());
        result.put("pages", userIPage.getPages());
        result.put("total", userIPage.getTotal());
        return result;
    }

    /**
     * @Description: 修改用户状态
     * @Param [id, loginFlag]
     * @Return com.yunyi.common.core.domain.AjaxResult
     * @Throws
     **/
    @PutMapping("/changeLoginFlag")
    @Log(title = "用户管理", businessType=BusinessType.UPDATE)
    public AjaxResult changeLoginFlag(Integer id, String loginFlag) {
        UpdateWrapper<SysUser> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id)
                .set("update_by", SecurityUtils.getLoginUser().getUsername())
                .set("update_date", new Date())
                .set("login_flag", loginFlag);
        if (userService.update(wrapper)) {
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改失败");
    }

    /**
     * @Description: 获取全部角色
     * @Param []
     * @Return com.yunyi.common.core.domain.AjaxResult
     * @Throws
     **/
    @GetMapping("/allRole")
    public AjaxResult allRole() {
        return AjaxResult.success(roleService.list());
    }

    /**
     * 根据职位获取所有用户
     * @return
     */
    @GetMapping("/get/list")
    public AjaxResult list(String jobName){
        return AjaxResult.success(userService.findUsers(jobName));
    }

    /**
     * @Description: 根据用户id获取详细信息
     * @Param [id]
     * @Return com.yunyi.common.core.domain.AjaxResult
     * @Throws
     **/
    @GetMapping("/getUserInfo/{id}")
    public AjaxResult getUserInfo(@PathVariable Integer id) {
        SysUser user = userService.getOne(new QueryWrapper<SysUser>().eq("id", id));
        List<Long> roleIds = roleService.selectRoleListByUserId(id.longValue());
        user.setRoleIds(roleIds.toArray(new Long[roleIds.size()]));
        user.setPassword("");
        return AjaxResult.success(user);
    }

    /**
     * @Description: 修改用户信息
     * @Param [user]
     * @Return com.yunyi.common.core.domain.AjaxResult
     * @Throws
     **/
    @PostMapping("/updateUser")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    public AjaxResult updateUser(@RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user))
        {
            return AjaxResult.error("修改用户'" + user.getLogin_name() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getMobile()) && !userService.checkPhoneUnique(user))
        {
            return AjaxResult.error("修改用户'" + user.getLogin_name() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return AjaxResult.error("修改用户'" + user.getLogin_name() + "'失败，邮箱账号已存在");
        }

        if (userService.updateUserInfo(user)) {
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改失败");
    }

    /**
     * @Description: 新增用户信息
     * @Param [user]
     * @Return com.yunyi.common.core.domain.AjaxResult
     * @Throws
     **/
    @PostMapping("/addUser")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    public AjaxResult addUser(@RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user))
        {
            return AjaxResult.error("新增用户'" + user.getLogin_name() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getMobile()) && !userService.checkPhoneUnique(user))
        {
            return AjaxResult.error("新增用户'" + user.getLogin_name() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return AjaxResult.error("新增用户'" + user.getLogin_name() + "'失败，邮箱账号已存在");
        }

        if (userService.addUserInfo(user)) {
            return AjaxResult.success("新增成功");
        }
        return AjaxResult.error("新增失败");
    }

    /**
     * @Description: 删除用户信息
     * @Param [id]
     * @Return com.yunyi.common.core.domain.AjaxResult
     * @Throws
     **/
    @DeleteMapping("/delUser/{ids}")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    public AjaxResult deleteUser(@PathVariable Integer[] ids) {
        int result = 0;
        for (Integer id : ids) {
            UpdateWrapper<SysUser> wrapper = new UpdateWrapper<>();
            wrapper.set("del_flag", "1")
                    .set("update_by", SecurityUtils.getUsername())
                    .set("update_date", new Date())
                    .eq("id", id);
            if (userService.update(wrapper)) { result ++; }
        }
        if (result == ids.length) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    @PutMapping("/resetPwd/{id}")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    public AjaxResult resetPwd(@PathVariable Integer id) {
        UpdateWrapper<SysUser> wrapper = new UpdateWrapper<>();
        wrapper.set("password", SecurityUtils.encryptPassword("112233445566"))
                .set("update_by", SecurityUtils.getUsername())
                .set("update_date", new Date())
                .eq("id", id);
        if (userService.update(wrapper)) {
            return AjaxResult.success("重置成功");
        }
        return AjaxResult.error("重置失败");
    }

}
